#include "sdl.h"
#include "errorscreen.h"
SDL_Surface * screen;

int init_sdl()
{
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        exit(1);
    }

    if (TTF_Init() == -1)
    {
        exit(1);
    }

    screen = SDL_SetVideoMode(480, 272, 16, SDL_SWSURFACE|SDL_DOUBLEBUF);
    if(!screen)
    {
        exit(1);
    }

#ifdef PSP
    SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    SDL_JoystickEventState(SDL_ENABLE);
#endif

    SDL_EnableKeyRepeat(150, 50);

    return 1;
}

TTF_Font* sdl_load_font(const char* file, int ptsize)
{
    TTF_Font* tmpfont;
    tmpfont = TTF_OpenFont(file, ptsize);
    if (tmpfont == NULL)
    {
        char msg[100];
        sprintf(msg,"Unable to load font: %s %s \n", file, TTF_GetError());
        app_error(msg);
        // Handle the error here.
    }
    return tmpfont;
}

SDL_Surface *sdl_draw_text(TTF_Font *fonttodraw, char fgR, char fgG, char fgB, char fgA,
                      char bgR, char bgG, char bgB, char bgA, const char* text, textquality quality)
{
    SDL_Color tmpfontcolor = {fgR,fgG,fgB,fgA};
    SDL_Color tmpfontbgcolor = {bgR, bgG, bgB, bgA};
    SDL_Surface *resulting_text;

    if (quality == solid) resulting_text = TTF_RenderUTF8_Solid(fonttodraw, text, tmpfontcolor);
    else if (quality == shaded) resulting_text = TTF_RenderUTF8_Shaded(fonttodraw, text, tmpfontcolor, tmpfontbgcolor);
    else if (quality == blended) resulting_text = TTF_RenderUTF8_Blended(fonttodraw, text, tmpfontcolor);

    if(resulting_text == NULL)
    {
        char msg[50];
        sprintf(msg, "Unable to create text surface: %s\n", SDL_GetError() );

        app_error(msg);
    }
    return resulting_text;
}

void sdl_clear_screen(char r, char g, char b)
{
    SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, r, g, b));
}

void sdl_paint_surface(SDL_Surface *surface, SDL_Rect *dstrect)
{
    SDL_BlitSurface(surface, NULL, screen, dstrect);
}

SDL_Surface * sdl_load_image(char* img)
{
    SDL_Surface * image = IMG_Load(img);
    if(!image)
    {
        char msg[50];
        sprintf(msg,"IMG_Load: %s\n", IMG_GetError());
        app_error(msg);
    }

    return image;
}

void sdl_flip()
{
    SDL_Flip(screen);
}
